
from django.shortcuts import render,HttpResponse
from django.http import JsonResponse
from mall import models
from PIL import Image,ImageDraw,ImageFont
# Create your views here.

def home(request):
    """
    首页
    """
    goods_list = models.Goods.objects.all()
    print("已向home界面传输goods_list")
    category_list = models.Category.objects.all()
    print("已向home界面传输category_list")
    if request.session.get('User_name') is None:
        return render(request,'mall_home.html',{'goods_list':goods_list,'category_list':category_list})
    else:
        return render(request,'mall_home.html',{'goods_list':goods_list,'category_list':category_list,'username':request.session.get('User_name')})



def login(request):
    if request.method == 'GET':
        return render(request, 'user_login.html')
    elif request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        if username == 'admin' and password == 'admin':
            return render(request, 'mall_admin.html')
        User = models.User.objects.filter(username=username,password=password)
        if User:
            goods_list = models.Goods.objects.all()
            category_list = models.Category.objects.all()
            for user in User:
                request.session['User_id'] = user.id
                request.session['User_name'] = user.username
                # 创建订单
                order = models.Order.objects.create(user=user,total_price=0,status=0)
                print("已创建订单")
                request.session['Order_id'] = order.id
            return render(request,'mall_home.html',{'username':username,'goods_list':goods_list,'category_list':category_list})
        else:
            return render(request, 'user_login.html', {'msg': '用户名或密码错误'})


def logout(request):
    """
    退出登录
    """
    # 退出登录，清空session
    # 如果退出登录时，订单总价为0，删除订单
    if request.session.get('Order_id') is not None:
        order = models.Order.objects.get(id=request.session.get('Order_id'))
        if order.total_price == 0:
            order.delete()
            print("未购买任何东西，已删除订单")

    request.session.flush()
    goods_list = models.Goods.objects.all()
    category_list = models.Category.objects.all()
    return render(request,'mall_home.html',{'goods_list':goods_list,'category_list':category_list})

def register(request):
    if request.method == 'GET':
        return render(request, 'user_register.html')
    elif request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        password_2 = request.POST.get('password_2')
        User=models.User.objects.filter(username=username)
        if User:
            return render(request, 'user_register.html', {'enroll_error': '用户名已存在'})
        elif password != password_2:
            return render(request, 'user_register.html', {'enroll_error': '两次密码不同，请重试'})
        elif username == '':
            return render(request, 'user_register.html', {'enroll_error': '用户名不能为空'})
        elif password == '':
            return render(request, 'user_register.html', {'enroll_error': '密码不能为空'})
        elif password == password_2 and username != '':
            models.User.objects.create(username=username,password=password)
            return render(request, 'user_login.html', {'msg': '注册成功，请登录'})




def join_cart(request ,id):
    """
    加入购物车
    """
    goods_list = models.Goods.objects.all()
    category_list = models.Category.objects.all()

    if request.session.get('User_name') is None:
        return render(request, 'user_login.html', {'msg': '请先登录'})
    elif request.method == 'GET':
        if request.session.get('Order_id') is None:
            # 如果没有订单，创建订单
            user = models.User.objects.get(id=request.session.get('User_id'))
            order = models.Order.objects.create(user=user,total_price=0,status=0)
            request.session['Order_id'] = order.id
        else:
            # 如果有订单，找到订单
            order = models.Order.objects.get(id=request.session.get('Order_id'))
            goods = models.Goods.objects.get(id=id)


            if goods.stock-1 < 0:
                return render(request,'mall_home.html',{'username':request.session.get('User_name'),'msg':'库存不足','goods_list':goods_list,'category_list':category_list})
            else:
                #在orderGoods里面找到对应的商品，如果有，数量加一，如果没有，新建一个
                order_goods = models.OrderGoods.objects.filter(order=order,goods=goods)
                if order_goods:
                    order_goods = models.OrderGoods.objects.get(order=order,goods=goods)
                    order_goods.number += 1

                    order_goods.save()
                else:
                    models.OrderGoods.objects.create(order=order, goods=goods, number=1)
                order.total_price += goods.price
                goods.stock -= 1
                goods.save()
                order.save()
            # 减少库存

            return render(request,'mall_home.html',{'username':request.session.get('User_name'),'msg':'加入购物车成功','goods_list':goods_list,'category_list':category_list})

def show_cart(request):
    """
    购物车
    """
    if request.session.get('User_name'):
        if request.session.get('Order_id') is None:
            # 如果没有订单，创建订单
            user = models.User.objects.get(id=request.session.get('User_id'))
            order = models.Order.objects.create(user=user,total_price=0,status=0)
            request.session['Order_id'] = order.id
        order = models.Order.objects.get(id=request.session.get('Order_id'))
        order_goods_list = models.OrderGoods.objects.filter(order=order)
        goods_list = models.Goods.objects.all()
        return render(request, 'my_cart.html',{'order_goods_list': order_goods_list, 'username': request.session.get('User_name'),'goods_list':goods_list,'order':order})
    else:
        return render(request, 'user_login.html', {'msg': '请先登录'})

#删除购物车的选项
def remove_cart(request,id):
    """
    删除购物车的选项
    """
    order_goods = models.OrderGoods.objects.get(id=id)
    order = models.Order.objects.get(id=request.session.get('Order_id'))
    order.total_price -= order_goods.goods.price * order_goods.number
    order_goods.goods.stock += order_goods.number
    order_goods.goods.save()
    order_goods.delete()
    order.save()
    order_goods_list = models.OrderGoods.objects.filter(order=order)
    goods_list = models.Goods.objects.all()
    return render(request,'my_cart.html',{ 'username': request.session.get('User_name'),'msg':'删除成功','order_goods_list':order_goods_list,'goods_list':goods_list,'order':order})


def show_recommend(request):
    """
    推荐
    通过recommend 表里的id，从goods表里找到对应的商品(已废弃)

    可以考虑通过销量来推荐商品（取个前三）
    或者通过保质期（不过这个要另外修改数据库）
    """
    # 先删掉recommend表里status为 1 的推荐商品 保证及时更新
    recommend_list = models.Recommend.objects.filter(status=1)
    for recommend in recommend_list:
        recommend.delete()

    #分组统计每个goods在order_goods表里的数量，然后排序，取前三
    goods_list = models.Goods.objects.all()
    for goods in goods_list:
        goods.order_goods_count = models.OrderGoods.objects.filter(goods=goods).count()
    goods_list = sorted(goods_list,key=lambda goods : goods.order_goods_count,reverse=True)
    goods_list = goods_list[:4]

    for goods in goods_list:
        print(goods.name+"销量"+str(goods.order_goods_count))

    # 加入到recommend表里，status 为1
    for goods in goods_list:
        if models.Recommend.objects.filter(goods=goods):
            print(goods.name+"已经在推荐里了")
        else:
            recommend = models.Recommend.objects.create(goods=goods,status=1)
            print(goods.name+"销量"+str(goods.order_goods_count) + "已加入推荐")

    recommend_list = models.Recommend.objects.all()
    goods_list = models.Goods.objects.all()
    if request.session.get('User_name'):
        return render(request,'recommend.html',{'recommend_list':recommend_list,'username':request.session.get('User_name'),'goods_list':goods_list})
    else:
        return render(request,'recommend.html',{'recommend_list':recommend_list,'goods_list':goods_list} )

def add(request):
    """
    添加商品种类，商品，推荐，没什么叼用，用admin就行
    """
    if request.method == 'GET':
        return render(request, 'mall_admin.html')
    elif request.method == 'POST':
        if request.POST.get('category_name'):
            category = request.POST.get('category_name')
            models.Category.objects.create(name=category)
            return render(request, 'mall_admin.html', {'msg': '商品种类添加成功'})
        if request.POST.get('goods_name'):
            goods_name = request.POST.get('goods_name')
            goods_price = request.POST.get('goods_price')
            goods_category = request.POST.get('category_id')
            goods_description = request.POST.get('goods_description')
            goods = models.Goods.objects.create(name=goods_name,price=goods_price,description=goods_description,category_id=goods_category)
            return render(request, 'mall_admin.html', {'msg': '商品添加成功'})
        if request.POST.get('recommend_name'):
            recommend_name= request.POST.get('recommend_name')
            goods = models.Goods.objects.get(name=recommend_name)
            recommend = models.Recommend.objects.create(goods_id=goods.id)
            return render(request, 'mall_admin.html', {'msg': '推荐添加成功'})


def confirm_order(request):
    """
    确认订单
    """
    goods_list = models.Goods.objects.all()
    print("已向home界面传输goods_list")
    category_list = models.Category.objects.all()
    print("已向home界面传输category_list")
    order = models.Order.objects.get(id=request.session.get('Order_id'))
    if order.total_price == 0:
        return render(request,'mall_home.html',{'msg':'订单为空','username':request.session.get('User_name'),'goods_list':goods_list,'category_list':category_list})
    else:
        order.status = 1
        order.save()
        #新建订单
        user = models.User.objects.get(id=request.session.get('User_id'))
        order = models.Order.objects.create(user=user,total_price=0,status=0)
        request.session['Order_id'] = order.id

        return render(request,'mall_home.html',{'msg':'订单已确认','username':request.session.get('User_name'),'goods_list':goods_list,'category_list':category_list})

def user_info(request):
    """
    个人信息
    """
    if request.session.get('User_name'):
        user = models.User.objects.get(id=request.session.get('User_id'))
        order_list = models.Order.objects.filter(user=user,status=1)
        return render(request,'user_info.html',{'username':request.session.get('User_name'),'order_list':order_list})
    else:
        return render(request, 'user_login.html', {'msg': '请先登录'})
    